<script setup lang="ts">
import { ref, onBeforeMount } from "vue";
import { queryDictChild, deleteDict } from "@/api/dict";
import SaveOrUpdate from "./SaveOrUpdate.vue";
import { ElMessage, ElMessageBox } from "element-plus";
//绑定表格
const tableData = ref([]);
//是否显示
const isShow = ref(false);

const saveUpdate = ref();
//定义属性
const props = defineProps({
  pid: {
    type: Number,
    required: true
  }
});

//查询列表
async function init() {
  let res = await queryDictChild(props.pid);
  if (res.code == 200) {
    tableData.value = res.data;
  }
}

//新增字典
function add() {
  isShow.value = true;
  saveUpdate.value.init(props.pid);
}

//修改字典
function update(row) {
  //根据
  isShow.value = true;
  saveUpdate.value.init(props.pid, row);
}

//删除字典
//删除当前行数据
async function deleteData(id) {
  ElMessageBox.confirm("确定要删除数据？", "删除", {
    confirmButtonText: "删除",
    cancelButtonText: "关闭",
    type: "warning"
  })
    .then(async () => {
      let res = await deleteDict(id);
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: "删除成功"
        });
        // 在删除成功后调用 initData 函数刷新页面数据
        init();
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除"
      });
      // 在删除成功后调用 initData 函数刷新页面数据
      init();
    });
}
onBeforeMount(() => {
  init();
});
</script>

<template>
  <div>
    <div style="text-align: right">
      <el-button type="primary" @click="add">新增字典</el-button>
    </div>

    <el-table :data="tableData" style="width: 100%" border>
      <el-table-column
        type="index"
        label="id"
        width="180"
        header-align="center"
      />
      <el-table-column
        prop="code"
        label="编码"
        width="180"
        header-align="center"
      />
      <el-table-column prop="name" label="名称" header-align="center" />
      <el-table-column
        prop="sorts"
        label="排序"
        width="180"
        header-align="center"
      />
      <el-table-column
        prop="createtime"
        label="创建时间"
        width="180"
        header-align="center"
      />
      <el-table-column label="操作" header-align="center">
        <template v-slot="{ row }">
          <div class="button-container">
            <el-button type="primary" @click="update(row)">修改</el-button>
            <el-button type="danger" @click="deleteData(row.id)"
              >删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <SaveOrUpdate
      ref="saveUpdate"
      :visible="isShow"
      @close="isShow = false"
      @refreshData="init"
    />
  </div>
</template>

<style scoped lang="scss">
.button-container {
  text-align: center;
}

.button-container .el-button {
  margin: 0 5px; /* 可根据需要调整按钮之间的间距 */
}
</style>
